package com.example.musictutor.services.listeners;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.example.musictutor.services.KeyBoard;
import com.example.musictutor.services.RecordSong;
import com.example.musictutor.views.KeyButton;

public class OnKeyTouchedListener implements OnTouchListener {

	private boolean mNoteComplete;
	
	//private class DurationRunnable implements 
	private class DurationRunnable implements Runnable {

		private KeyButton keyButton;
		
		public DurationRunnable(KeyButton keyButton) {
			super();
			this.keyButton = keyButton;
		}
		
		@Override
		public void run() {
			int duration = 0;
			
			while(!mNoteComplete)
			{
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					Log.e("OnKeyTouchedListener", e.getStackTrace().toString());
				}
				
				duration += 20;
			}
			
			RecordSong recordSong = RecordSong.getInstance();
			recordSong.AddNote(keyButton.getNote(), duration);
		}
		
	};
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		RecordSong recordSong = RecordSong.getInstance();
		
		if(event.getAction() == MotionEvent.ACTION_DOWN)
		{
			Log.d("Recording", "Action Down. Class: " + this.hashCode());
			KeyButton keyButton = (KeyButton) v;
			keyButton.startPlayer();

			if(recordSong.getState() == RecordSong.STATE_RECORDING)
			{
				mNoteComplete = false;
				Thread thread = new Thread(new DurationRunnable(keyButton));
				thread.start();
			}
		}
		if(event.getAction() == MotionEvent.ACTION_UP)
		{
			KeyButton keyButton = (KeyButton) v;
			keyButton.stopPlayer();

			if(recordSong.getState() == RecordSong.STATE_RECORDING)
				mNoteComplete = true;
		}
		
		return false;
	}
	
	
	
}
